package handlers

import (
	json2 "encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
	"xc/cache"
	"xc/models"
	"xc/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "字段为空",
		})
		return
	}

	redis_login_key := "login_error_"
	errcount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errcount >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	var user models.User
	models.DB.Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errcount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁两小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&data)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}

func UserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var role []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid=roles.id").
		Where("user_roles.uid=?", uid).Debug().Find(&role)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": role,
	})
	return
}

func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var node []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid=nodes.id").
		Where("role_nodes.rid=?", rid).Debug().Find(&node)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": node,
	})
	return
}

func CarAdd(c *gin.Context) {
	car_id := c.PostForm("car_id")
	car_name := c.PostForm("car_name")
	car_num := c.PostForm("car_num")
	car := models.Car{
		CarId:   car_id,
		CarName: car_name,
		CarNum:  car_num,
	}
	models.DB.Create(&car)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": car,
	})
	return
}

func OrderAdd(c *gin.Context) {
	order_id := c.PostForm("order_id")
	fa_address := c.PostForm("fa_address")
	sh_addrsss := c.PostForm("sh_address")
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	order := models.Order{
		OrderId:   order_id,
		FaAddress: fa_address,
		ShAddress: sh_addrsss,
		Cid:       cid,
	}
	models.DB.Create(&order)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": order,
	})
	return
}

func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var orderList []models.OrderList

	redis_list_key := "list_error_" + strconv.Itoa(page)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if cacheJson == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN cars ON cars.id=orders.id").
			Select(
				"orders.order_id as OrderId",
				"orders.fa_address as FaAddress",
				"orders.sh_address as AhAddress",
				"cars.car_id as CarId",
				"cars.car_name as CarName",
				"cars.car_num as CarNum",
			).
			Offset(offset).Limit(size).Debug().Find(&orderList)
		json, _ := json2.Marshal(&orderList)
		cache.Rdb.Set(cache.Ctx, redis_list_key, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &orderList)
	}

	var count int64
	models.DB.Model(&models.Order{}).Count(&count)
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  orderList,
		"count": count,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var order models.Order

	redis_detail_key := "detail_error" + id
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if cacheJson == "" {
		models.DB.Where("id=?", id).First(&order)
		json, _ := json2.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &order)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": order,
	})
	return
}
